基本思路:通过for循环遍历字符串,通过String类中的charAt(int index)方法返回指定索引的字符,然后通过两种方法判断是否大小写字母或数字并进行统计,最后输出结果
方法一:
String s = "hjsdg639NJDHjkfh6439hbdJKSHEFLhjsdg";
int upper = 0;
int lower = 0;
int num = 0;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(c>='A' && c<='Z') {
upper++;
}
if(c>='a' && c<='z') {
lower++;
}
if(c>='0' && c<='9') {
num++;
}
}
System.out.println("大写字母出现次数为"+upper+"次,小写字母出现次数为"+lower+"次,数字出现次数为"+num+"次");
方法二:
String s = "hjsdg639NJDHjkfh6439hbdJKSHEFLhjsdg";
int upper = 0;
int lower = 0;
int num = 0;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(Character.isUpperCase(c)) {
upper++;
}
if(Character.isLowerCase(c)) {
lower++;
}
if(Character.isDigit(c)) {
num++;
}
}
System.out.println("大写字母出现次数为"+upper+"次,小写字母出现次数为"+lower+"次,数字出现次数为"+num+"次");